<template>
  <div class="login">
    <van-nav-bar
      title="登录"
    />
    <van-cell-group>
      <van-field
        v-model="mobile"
        :error-message="mobile_errmsg"
        required
        label="用户名"
        placeholder="请输入用户名"
        @input="mobileValidate();codeValidate()"
      />
      <van-field
        v-model="code"
        required
        center
        :error-message="code_errmsg"
        clearable
        label="验证码"
        placeholder="请输入短信验证码"
        @input="mobileValidate();codeValidate()"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode()">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn-wrap">

      <van-button type="primary" @click="login()">登录</van-button>
    </div>
  </div>
</template>

<script>
import { reqGetUserInfo, reqSendCode } from '@/api/user'
export default {
  data() {
    return {
      mobile: '13912345678',
      code: '246810',
      mobile_errmsg: '',
      code_errmsg: ''
    }
  },

  methods: {
    async login() {
      if (!this.mobileValidate() || !this.codeValidate()) return this.$toast.fail('手机号或验证码输入错误')
      if (this.mobileValidate() || this.codeValidate()) {
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          overlay: true,
          duration: 0 // 展示时长，不限时间

        })
      }
      try {
        const res = await reqGetUserInfo(this.mobile, this.code)
        // 存token
        this.$store.commit('user/setToken', res.data)
        this.$toast.success('登录成功')
        const path = this.$router.history.current.query.toback || '/'
        this.$router.push(path)
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    },
    async sendCode() {
      if (!this.mobileValidate() || !this.codeValidate()) return this.$toast.fail('手机号或验证码输入错误')
      try {
        await reqSendCode(this.mobile)
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    },

    // 需求：让表单实现实时校验input ，发送验证码时和登录时判断校验是否通过。
    mobileValidate() {
      if (!this.mobile) {
        this.mobile_errmsg = '请输入手机号'
        return false
      }
      if (!/^13[0-9]{1}\d{8}$/.test(this.mobile)) {
        this.mobile_errmsg = '手机号校验失败'
        return false
      }
      this.mobile_errmsg = ''

      return true
    },
    codeValidate() {
      if (!this.code) {
        this.code_errmsg = '请输入验证码'
        return false
      }
      if (!/^\d{6}$/.test(this.code)) {
        this.code_errmsg = '验证码校验失败'
        return false
      }
      this.code_errmsg = ''
      this.$toast.fail('验证码校验成功')
      return true
    }
  }

}
</script>

<style lang="scss" scoped>
.login {
  .btn-wrap {
    padding: 20px;
    .van-button {
      width: 100%;
      color: #fff;
      border-radius: 5px;
    }
  }
}
</style>
